//
// XKeybinder.cs
//
// Copyright (C) 2004-2007 Alex Graveley <alex@beatniksoftware.com>
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace Dashboard.Latte
{
	public static class XKeybinder 
	{
		public delegate void BindkeyHandler (string key, IntPtr user_data);

		private static List<Binding> bindings = new List<Binding> ();
		private static BindkeyHandler key_handler = new BindkeyHandler (KeybindingPressed);

		static XKeybinder ()
		{
			try {
				tomboy_keybinder_init ();
			} catch (DllNotFoundException) {
				Console.WriteLine ("libtomboy not found - keybindings will not work");
			}
		}

		private static void KeybindingPressed (string keystring, IntPtr user_data)
		{
			foreach (Binding binding in bindings) {
				if (binding.Keystring == keystring) {
					binding.Handler (null, new EventArgs ());
				}
			}
		}

		public static void Bind (string keystring, EventHandler handler)
		{
			Binding binding = new Binding ();
			binding.Keystring = keystring;
			binding.Handler = handler;
			bindings.Add (binding);
			
			tomboy_keybinder_bind (binding.Keystring, key_handler);
		}

		public static void Unbind (string keystring)
		{
			foreach (Binding binding in bindings) {
				if (binding.Keystring == keystring) {
					tomboy_keybinder_unbind (binding.Keystring, key_handler);
					bindings.Remove (binding);

					break;
				}
			}
		}

		public static void UnbindAll ()
		{
			foreach (Binding binding in bindings) {
				tomboy_keybinder_unbind (binding.Keystring, key_handler);
			}

			bindings.Clear ();
		}

		private struct Binding {
			internal string Keystring;
			internal EventHandler Handler;
		}

		[DllImport("libtomboy")]
		static extern void tomboy_keybinder_init ();

		[DllImport("libtomboy")]
		static extern void tomboy_keybinder_bind (string keystring, BindkeyHandler handler);

		[DllImport("libtomboy")]
		static extern void tomboy_keybinder_unbind (string keystring, BindkeyHandler handler);
	}
}
